package com.ruyuan.seckilling.render.service.impl;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.ruyuan.seckilling.render.service.FileService;
import com.ruyuan.starter.jedis.CacheSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author zhonghuashishan
 */
@Service
public class FileServiceImpl implements FileService {

    // 缓存的是模板文件的内容
    private final Cache<String, String> cache = CacheBuilder.newBuilder()
            .maximumSize(100)
            .expireAfterWrite(30, TimeUnit.MINUTES)
            .build();

    // 这里是把模板文件，和渲染后的静态页面保存到Redis上去了
    @Autowired
    private CacheSupport cacheSupport;

    public String download(String url) {
        try {
            return cache.get(url, () -> cacheSupport.get(url));
        } catch (ExecutionException e) {
            e.printStackTrace();
            return null;
        }
    }

    public String upload(String content) {
        String url = UUID.randomUUID().toString();
        cacheSupport.set(url, content);
        return url;
    }

}